package com.lxy.cloud.mqtt.client.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

import static com.lxy.cloud.mqtt.client.config.MqttConfig.CHANNEL_NAME_OUT;

/**
 * @Author: lxy
 * @Date: 2020/9/6 23:24
 * @Desc:  生产者配置
 */
@Configuration
public class MqttOutConfig {

    @Autowired
    private MqttPahoClientFactory mqttClientFactory;

    @Autowired
    private MqttConfig mqttConfig;
    /**
     * MQTT信息通道（生产者）
     *
     * @return {@link org.springframework.messaging.MessageChannel}
     */
    @Bean(name = CHANNEL_NAME_OUT)
    public MessageChannel mqttOutboundChannel() {
        return new DirectChannel();
    }

    /**
     * MQTT消息处理器（生产者）
     *
     * @return {@link org.springframework.messaging.MessageHandler}
     */
    @Bean
    @ServiceActivator(inputChannel = CHANNEL_NAME_OUT)
    public MessageHandler mqttOutbound() {
        MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(
                mqttConfig.getProducerClientId(),
                mqttClientFactory);
        messageHandler.setAsync(true);
        return messageHandler;
    }
}
